package net.organizer.ui.actionhandler;

import java.util.HashMap;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import net.organizer.dao.Domain;
import net.organizer.dao.OrgPerson;
import net.organizer.dao.Person;

import org.json.JSONArray;
import org.json.JSONObject;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class PersonGetListActionHandler extends ActionHandlerBase {
	private static final Logger logger = Logger.getLogger(PersonGetListActionHandler.class.getName());
	
	@Override
	public void handleAction(HttpServletRequest req, JSONObject respJSONObject) throws Exception {
		logger.fine("handleAction");
		Long orgId = getParamValueAsLong(req, "orgId", false);
		logger.fine("orgId: " + orgId);
		//Thread.sleep(3000);
//		if(1==1){
//			throw new RuntimeException("fail!");
//		}
		Objectify ofy = ObjectifyService.begin();
		HashMap<Long,Person> persons = new HashMap<Long,Person>();
		for(Person person : ofy.query(Person.class).ancestor(Domain.getKey("domain1")).list()){
			persons.put(person.getId(), person);
		}
		
		// if there is an orgId, then get the orgPersons and remove them from the list
		if(orgId != null){
			Domain domain = new Domain();
			domain.setName("domain1");
			for(OrgPerson orgPerson : ofy.query(OrgPerson.class).ancestor(domain.getKey()).filter("orgId = ", orgId).list()){
				persons.remove(orgPerson.getPersonId());
			}			
		}
		
		logger.fine(String.format("persons.size(): %d", persons.size()));
		JSONArray  jSONArray = new JSONArray();
		for(Person person : persons.values()){
			jSONArray.put(person.toJSONObject());
		}
		respJSONObject.put("persons", jSONArray);
	}
}
